<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>一个简单的案例带你了解并解决跨域以及跨域携带cookie的问题 | DiDi</title>
  <meta name="description" content="什么是跨域关于什么是跨域的问题相信很多开发者都耳熟能详，并且也能很好地回答出来，这里我就简单解释一下不多加赘述了，简单来说就是你在当前网页的域名下去请求另一个域名下的资源就会出现跨域的情况。请求地址的协议，域名，端口号三者只要有一个和当前的不一样就是跨域。对于前端开发者有时候可能不那么容易去调式一个跨域的情况，本文就用一个简单的例子可以让前端开发者很好的理解并去解决这个问题。 一个简单的跨域示例">
<meta property="og:type" content="article">
<meta property="og:title" content="一个简单的案例带你了解并解决跨域以及跨域携带cookie的问题">
<meta property="og:url" content="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/how-to-deal-with-cross-domain/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="什么是跨域关于什么是跨域的问题相信很多开发者都耳熟能详，并且也能很好地回答出来，这里我就简单解释一下不多加赘述了，简单来说就是你在当前网页的域名下去请求另一个域名下的资源就会出现跨域的情况。请求地址的协议，域名，端口号三者只要有一个和当前的不一样就是跨域。对于前端开发者有时候可能不那么容易去调式一个跨域的情况，本文就用一个简单的例子可以让前端开发者很好的理解并去解决这个问题。 一个简单的跨域示例">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture1.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture2.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture3.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture4.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture5.png">
<meta property="article:published_time" content="2023-02-08T02:48:36.000Z">
<meta property="article:modified_time" content="2023-12-16T07:45:36.098Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="跨域">
<meta property="article:tag" content="cookie">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://guoyayunhappy.gitee.io/didiblog/images/cross-domain/cross-domain-picture1.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/how-to-deal-with-cross-domain/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="images/favatar/idesign-logo.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/didiblog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 7.3.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://gitee.com/GuoyayunHappy" target="_blank">
          <img class="img-circle img-rotate" src="/didiblog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">一枚@大帅锅</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">CV工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Shanghai, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/didiblog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/didiblog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/didiblog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/didiblog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/didiblog/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/didiblog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>让coding更有趣!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/JS/">JS</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/TS/">TS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/">网站</a><span class="category-list-count">1</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/html/">html</a><span class="category-list-count">1</span></li></ul></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTML/" rel="tag">HTML</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTP/" rel="tag">HTTP</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTPS/" rel="tag">HTTPS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/JS/" rel="tag">JS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Nodejs/" rel="tag">Nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Token/" rel="tag">Token</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/cookie/" rel="tag">cookie</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/typescript/" rel="tag">typescript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/didiblog/tags/HTML/" style="font-size: 13px;">HTML</a> <a href="/didiblog/tags/HTTP/" style="font-size: 13px;">HTTP</a> <a href="/didiblog/tags/HTTPS/" style="font-size: 13px;">HTTPS</a> <a href="/didiblog/tags/JS/" style="font-size: 13px;">JS</a> <a href="/didiblog/tags/Nodejs/" style="font-size: 13px;">Nodejs</a> <a href="/didiblog/tags/Token/" style="font-size: 13px;">Token</a> <a href="/didiblog/tags/cookie/" style="font-size: 13px;">cookie</a> <a href="/didiblog/tags/js/" style="font-size: 13px;">js</a> <a href="/didiblog/tags/typescript/" style="font-size: 13px;">typescript</a> <a href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" style="font-size: 13px;">性能优化</a> <a href="/didiblog/tags/%E7%AE%97%E6%B3%95/" style="font-size: 13.5px;">算法</a> <a href="/didiblog/tags/%E7%BC%93%E5%AD%98/" style="font-size: 13px;">缓存</a> <a href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 14px;">设计模式</a> <a href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" style="font-size: 13px;">跨域</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/07/">七月 2025</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/06/">六月 2025</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/03/">三月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/02/">二月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/12/">十二月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/10/">十月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/02/">二月 2023</a><span class="archive-list-count">7</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/28/browser-cache/" class="title">用代码实践浏览器的强缓存和协商缓存</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-28T06:54:53.000Z" itemprop="datePublished">2025-07-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/didiblog/categories/JS/">JS</a>
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/18/tail-call-optimization/" class="title">尾调用优化</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-18T11:53:08.000Z" itemprop="datePublished">2025-07-18</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/06/17/interview/" class="title">interview</a>
              </p>
              <p class="item-date">
                <time datetime="2025-06-17T03:52:38.000Z" itemprop="datePublished">2025-06-17</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/03/03/find-hamilton-path/" class="title">Javascript实现寻找哈密尔顿回路</a>
              </p>
              <p class="item-date">
                <time datetime="2024-03-03T00:18:45.000Z" itemprop="datePublished">2024-03-03</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/02/21/better-to-know-signature-and-certificate/" class="title">一文读懂加密，摘要，数字签名和证书</a>
              </p>
              <p class="item-date">
                <time datetime="2024-02-21T03:22:45.000Z" itemprop="datePublished">2024-02-21</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-how-to-deal-with-cross-domain" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      一个简单的案例带你了解并解决跨域以及跨域携带cookie的问题
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/didiblog/2023/02/08/how-to-deal-with-cross-domain/" class="article-date">
	  <time datetime="2023-02-08T02:48:36.000Z" itemprop="datePublished">2023-02-08</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/">网站</a>►<a class="article-category-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/html/">html</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/didiblog/tags/cookie/" rel="tag">cookie</a>, <a class="article-tag-link-link" href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/didiblog/2023/02/08/how-to-deal-with-cross-domain/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h2 id="什么是跨域"><a href="#什么是跨域" class="headerlink" title="什么是跨域"></a>什么是跨域</h2><p>关于什么是跨域的问题相信很多开发者都耳熟能详，并且也能很好地回答出来，这里我就简单解释一下不多加赘述了，简单来说就是你在当前网页的域名下去请求另一个域名下的资源就会出现跨域的情况。请求地址的协议，域名，端口号三者只要有一个和当前的不一样就是跨域。对于前端开发者有时候可能不那么容易去调式一个跨域的情况，本文就用一个简单的例子可以让前端开发者很好的理解并去解决这个问题。</p>
<h3 id="一个简单的跨域示例"><a href="#一个简单的跨域示例" class="headerlink" title="一个简单的跨域示例"></a>一个简单的跨域示例</h3><ul>
<li>首先创建一个最简单的<code>index.html</code>页面，页面只包含一个<code>button</code>,点击这个按钮的时候会发送一个到<code>http://localhost:3030/user</code>的请求<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=&quot;en&quot;&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">&lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">&lt;meta name=&quot;viewport&quot; content=&quot;width=&lt;device-width&gt;, initial-scale=1.0&quot;&gt;</span><br><span class="line">&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;</span><br><span class="line">&lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;h2&gt;Test for Cross Domain&lt;/h2&gt;</span><br><span class="line">        &lt;button id=&quot;crossFetch&quot;&gt;Cross Fetch&lt;/button&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">const crossFetch = document.querySelector(&#x27;#crossFetch&#x27;);</span><br><span class="line"></span><br><span class="line">crossFetch.addEventListener(&#x27;click&#x27;, () =&gt; &#123;</span><br><span class="line">    fetch(&#x27;http://localhost:3030/user&#x27;).then(response =&gt; &#123;</span><br><span class="line">        return response.json();</span><br><span class="line">    &#125;).then(res =&gt; &#123;</span><br><span class="line">        console.log(res);</span><br><span class="line">    &#125;).catch((err) =&gt; &#123;</span><br><span class="line">        console.error(&#x27;set cookie error: &#x27;, err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure></li>
<li>然后创建一个文件<code>clientSide.js</code>, 一个最简单的<code>express</code>后台服务，让刚才那个页面在<code>http://localhost:8000</code>这个域名下运行，然后命令行运行<code>node clientSide.js</code><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&#x27;express&#x27;);</span><br><span class="line">const app = express();</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line">app.use(express.static(path.join(__dirname, &#x27;./public&#x27;)));</span><br><span class="line">app.listen(8000, () =&gt; &#123;</span><br><span class="line">    console.log(&#x27;listening port 8000...&#x27;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></li>
<li>打开浏览器输入<code>localhost:8000/index.html</code>,然后我们会看到一个只包含一个按钮的页面</li>
</ul>
<p><img src="/didiblog/images/cross-domain/cross-domain-picture1.png" alt="image.png"></p>
<ul>
<li>现在前端是有了，但是后端服务还没有，我们再创建一个文件<code>serverSide.js</code>，让这个后端服务运行在<code>3030</code>端口，并提供了一个<code>/user</code>获取user的接口，这个其实就是上面点击按钮要发送的地址。同样的启动这个服务<code>node serverSide.js</code>, 相信没有比这更简单的服务了。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&#x27;express&#x27;);</span><br><span class="line">const app = express();</span><br><span class="line"></span><br><span class="line">app.get(&#x27;/user&#x27;, (req, res) =&gt; &#123;</span><br><span class="line">    res.json(&#123;</span><br><span class="line">        name: &quot;jacky&quot;,</span><br><span class="line">        age: 23</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.listen(3030, () =&gt; &#123;</span><br><span class="line">    console.log(&#x27;listening port 3030&#x27;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></li>
<li>现在基本条件都准备好了，然后我们去点击页面的按钮去发送请求，这时候我们在网页的控制台会发现一个错误。这个错误就是我们开发中经常遇到的跨域问题。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Access to fetch at &#x27;http://localhost:3030/user&#x27; from origin &#x27;http://localhost:8000&#x27;</span><br><span class="line">has been blocked by CORS policy: No &#x27;Access-Control-Allow-Origin&#x27; header is </span><br><span class="line">present on the requested resource. If an opaque response serves your needs, </span><br><span class="line">set the request&#x27;s mode to &#x27;no-cors&#x27; to fetch the resource with CORS disabled.</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="通过引入第三方包cors来解决跨域问题"><a href="#通过引入第三方包cors来解决跨域问题" class="headerlink" title="通过引入第三方包cors来解决跨域问题"></a>通过引入第三方包<code>cors</code>来解决跨域问题</h3><h4 id="‘Access-Control-Allow-Origin’-这个是什么？"><a href="#‘Access-Control-Allow-Origin’-这个是什么？" class="headerlink" title="‘Access-Control-Allow-Origin’ 这个是什么？"></a>‘Access-Control-Allow-Origin’ 这个是什么？</h4><p> 在引入包之前我们看下这段报错内容说的是什么，<code>Access-Control-Allow-Origin</code>这个设置阻止了这次请求，这个设置其实就是后端通常用来限制请求的响应头配置，如果你想让你的资源不受限制，谁都可以访问，就可以设置一个通配符”*”：<br> <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">app.all(&#x27;*&#x27;, function(req, res, next) &#123; </span><br><span class="line">    res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;); </span><br><span class="line">    next();</span><br><span class="line"> &#125;);</span><br></pre></td></tr></table></figure><br>或者你也可以指定某些域名可以访问<br> <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">app.all(&#x27;*&#x27;, function(req, res, next) &#123; </span><br><span class="line">    res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;https://www.baidu.com&quot;); </span><br><span class="line">    next();</span><br><span class="line"> &#125;);</span><br></pre></td></tr></table></figure></p>
<h4 id="引入cors包来解决跨域问题"><a href="#引入cors包来解决跨域问题" class="headerlink" title="引入cors包来解决跨域问题"></a>引入<code>cors</code>包来解决跨域问题</h4><p> 我们可以通过<code>npm install cors</code>来安装第三方包，把它作为<code>express</code>的中间件设置进去，改过之后的<code>serverSide.js</code>就变成了如下这样,现在我们来重启一下这个文件<br> <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> const express = require(&#x27;express&#x27;);</span><br><span class="line">const app = express();</span><br><span class="line">const cors = require(&#x27;cors&#x27;)</span><br><span class="line"></span><br><span class="line">app.use(cors()) //不加参数就相当于：res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;); </span><br><span class="line">app.get(&#x27;/user&#x27;, () =&gt; &#123;</span><br><span class="line">    res.json(&#123;</span><br><span class="line">        name: &quot;jacky&quot;,</span><br><span class="line">        age: 23</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.listen(3030, () =&gt; &#123;</span><br><span class="line">    console.log(&#x27;listening port 3030&#x27;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><br> 现在刷新一下浏览器再去点击按钮，发现控制台的错误就没有了，跨域问题可以通过后端配置很好地解决了。</p>
<p><img src="/didiblog/images/cross-domain/cross-domain-picture2.png" alt="image.png"></p>
<h3 id="跨域如何携带cookie"><a href="#跨域如何携带cookie" class="headerlink" title="跨域如何携带cookie"></a>跨域如何携带cookie</h3><p>我们都知道<code>cookie</code>是前端非常重要的一种存储方式，经常用来保持用户的登录状态，那在跨域的情况下如何携带cookie呢？</p>
<ul>
<li>接下来我们来简单改下刚才的<code>index.html</code>文件,多添加一个<code>Login</code>按钮，这个按钮是用来向后端发送请求(可以理解为登录）后，后端会给浏览器设置一个<code>cookie</code>值。如截图所示<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=&quot;en&quot;&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">&lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">&lt;meta name=&quot;viewport&quot; content=&quot;width=&lt;device-width&gt;, initial-scale=1.0&quot;&gt;</span><br><span class="line">&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;</span><br><span class="line">&lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h2&gt;Test for Cross Domain&lt;/h2&gt;</span><br><span class="line">&lt;button id=&quot;Login&quot;&gt;Login&lt;/button&gt;</span><br><span class="line">&lt;button id=&quot;crossFetch&quot;&gt;Cross Fetch&lt;/button&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">const Login = document.querySelector(&#x27;#Login&#x27;);</span><br><span class="line">const crossFetch = document.querySelector(&#x27;#crossFetch&#x27;);</span><br><span class="line">crossFetch.addEventListener(&#x27;click&#x27;, () =&gt; &#123;</span><br><span class="line">    fetch(&#x27;http://localhost:3030/user&#x27;).then(response =&gt; &#123;</span><br><span class="line">        return response.json();</span><br><span class="line">        &#125;).then(res =&gt; &#123;</span><br><span class="line">        console.log(res);</span><br><span class="line">        &#125;).catch((err) =&gt; &#123;</span><br><span class="line">        console.error(&#x27;set cookie error: &#x27;, err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line">Login.addEventListener(&#x27;click&#x27;, () =&gt; &#123;</span><br><span class="line">    fetch(&#x27;/login&#x27;).then(response =&gt; &#123;</span><br><span class="line">        return response.json();</span><br><span class="line">    &#125;).then(res =&gt; &#123;</span><br><span class="line">        console.log(res);</span><br><span class="line">    &#125;).catch((err) =&gt; &#123;</span><br><span class="line">        console.error(&#x27;set cookie error: &#x27;, err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
更改后的<code>clientSide.js</code>文件如下：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&#x27;express&#x27;);</span><br><span class="line">const app = express();</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line">app.use(express.static(path.join(__dirname, &#x27;./public&#x27;)));</span><br><span class="line"></span><br><span class="line">app.get(&#x27;/login&#x27;, (req, res) =&gt; &#123;</span><br><span class="line">    res.cookie(&quot;user_id&quot;, &quot;123&quot;, &#123;</span><br><span class="line">        maxAge: 1000 * 60 * 60 * 2</span><br><span class="line">    &#125;);</span><br><span class="line">    res.json(&#123;</span><br><span class="line">        result: &quot;success&quot;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(8000, () =&gt; &#123;</span><br><span class="line">    console.log(&#x27;listening port 8000...&#x27;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<img src="/didiblog/images/cross-domain/cross-domain-picture3.png" alt="image.png"></li>
<li>现在点击按钮<code>Cross Fetch</code>, 我们在后端的请求<code>/user</code>接口里打印下看能不能获取刚才设置的cookie值 <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"> app.get(&#x27;/user&#x27;, (req, res) =&gt; &#123;</span><br><span class="line">    console.log(&#x27;cookie:&#x27;, req.headers.cookie);</span><br><span class="line">    res.json(&#123;</span><br><span class="line">        name: &quot;jacky&quot;,</span><br><span class="line">        age: 23</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
 很明显是<code>undefined</code>, 并不能获取前台发来的cookie值。</li>
</ul>
<p><img src="/didiblog/images/cross-domain/cross-domain-picture4.png" alt="image.png"><br>为什么会这样呢？因为我们在前端使用的<code>fetch</code>请求中有个参数叫作<code>credentials</code>，这个值是用来控制发送cookie的，它一共有三个值：</p>
<ol>
<li><code>same-origin</code> 同域名下可以携带cookie发送，这个值也是默认值</li>
<li><code>include</code> 允许跨域携带cookie发送</li>
<li><code>omit</code> 不携带cookie</li>
</ol>
<p>那这样就很好办了，我们把这个值设置成<code>include</code>不就好了，来我们再来改一下<code>index.html</code>：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">fetch(&#x27;http://localhost:3030/user&#x27;, &#123;</span><br><span class="line">        credentials: &#x27;include&#x27;</span><br><span class="line">    &#125;).then(response =&gt; &#123;</span><br><span class="line">        return response.json();</span><br><span class="line">&#125;)</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>看着很完美地样子，我们去刷新浏览器，再去点击<code>Cross Fetch</code>按钮，但是控制台又有了新的错误：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Access to fetch at &#x27;http://localhost:3030/user&#x27; from origin &#x27;http://localhost:8000&#x27;</span><br><span class="line">has been blocked by CORS policy: The value of the &#x27;Access-Control-Allow-Origin&#x27;</span><br><span class="line">header in the response must not be the wildcard &#x27;*&#x27; when the request&#x27;s credentials </span><br><span class="line">mode is &#x27;include&#x27;.</span><br></pre></td></tr></table></figure>
<p>简单总结就是，如果前端credentials设置成了<code>include</code>,那么后端的响应头<code>Access-Control-Allow-Origin</code>就不能设置为通配符“*”了。那我们只能再来去改下<code>serverSide.js</code>里的配置，我们指定域名而不是给通配符（其实通配符是不推荐使用的方法）来访问资源，查了下文档，可以传参给<code>cors</code>方法。这里设置了两个参数，一个<code>origin</code>指的就是指定域名，第二个<code>credentials</code>就是允许携带<code>cookie</code>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">app.use(cors(&#123;</span><br><span class="line">    origin: &#x27;http://localhost:8000&#x27;,</span><br><span class="line">    credentials: true</span><br><span class="line">&#125;));</span><br></pre></td></tr></table></figure>
<p>最后我们保存下文件重新运行下<code>serverSide.js</code>，然后刷新浏览器，点击<code>Cross Fetch</code>按钮，现在发现服务端就可以获取到<code>cookie</code>值了，跨域携带cookie的问题也很好地解决了。</p>
<p><img src="/didiblog/images/cross-domain/cross-domain-picture5.png" alt="image.png"></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>跨域是我们开发中经常遇到的问题，解决的办法有很多种，希望大家也可以动手去试试不同的解决方法，虽然都是一些基本的知识，但是积累的多了，当你再遇到类似的问题就可以很快地找到答案了，半夜码字不易，喜欢的小伙伴给个赞吧！！！</p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/how-to-deal-with-cross-domain/" title="一个简单的案例带你了解并解决跨域以及跨域携带cookie的问题" target="_blank" rel="external">https://guoyayunhappy.gitee.io/didiblog/2023/02/08/how-to-deal-with-cross-domain/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/GuoyayunHappy" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/didiblog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/GuoyayunHappy" target="_blank"><span class="text-dark">一枚@大帅锅</span><small class="ml-1x">CV工程师</small></a></h3>
        <div>个人简介。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/didiblog/2023/02/08/design-pub-sub/" title="发布-订阅模式-- 《Javascript 设计模式与开发实践》"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/didiblog/2023/02/07/hello-world/" title="Hello World"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/didiblog/js/plugin.min.js"></script>


<script src="/didiblog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/didiblog/',
        CONTENT_URL: '/didiblog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/didiblog/js/insight.js"></script>






   




   
    
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/valine"></script>
  <script type="text/javascript">
  var GUEST = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link';
  meta = meta.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#vcomments',
    verify: false,
    notify: false,
    appId: '',
    appKey: '',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: meta,
    pageSize: '10' || 10,
    visitor: false
  });
  </script>

     







</body>
</html>